package com.sanyue.springboot.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author: Guan
 **/
@Slf4j
@Controller
public class UpLoadController {
    @GetMapping("/upload.html")
    public String ToUpLoad(){
        return "upload";
    }

    @PostMapping("/upload")
    @ResponseBody
    public String load(@RequestParam("name") String name,
                       @RequestParam("email") String email,
                       @RequestParam("age") Integer age,
                       @RequestParam("job") String job,
                       @RequestParam("header")MultipartFile header,
                       @RequestParam("photos") MultipartFile[] photos) throws IOException {
        log.info("上传成功");
        System.out.println("name = " + name);
        System.out.println("email = " + email);
        System.out.println("age = " + age);
        System.out.println("job = " + job);
        System.out.println("header = " + header);
        System.out.println("photos = " + photos.length);

        //如果信息成功得到，保存信息到指定的目录/新建一个目录用于保存
        //1.现将文件保存到指定的目录
        if(!header.isEmpty()){ //处理单个头像
            String originalFilename = header.getOriginalFilename();
            header.transferTo(new File("D:\\test\\" + originalFilename));
        }
        //
        // if(photos.length > 0){
        //     for (MultipartFile photo : photos) {
        //         String originalFilename = photo.getOriginalFilename();
        //         photo.transferTo(new File("D:\\test\\" + originalFilename));
        //     }
        // }

        //2.将文件保存到动态创建的目录中:E:\code\SpringBoot\springboot-thymeleaf\target\classes\static\images\test

        //得到运行时的类路径
        //path = /E:/code/SpringBoot/springboot-thymeleaf/target/classes/
        String path = ResourceUtils.getURL("classpath:").getPath();
        System.out.println("path = " + path);
        File file = new File(path + "static/images/test/");
        //动态创建指定目录
        if (!file.exists()) {  //如果不存在这个目录，就创建目录
            file.mkdirs();
        }
        if(photos.length > 0){
            for (MultipartFile photo : photos) {
                String originalFilename = photo.getOriginalFilename();
                //需要指定保存文件的绝对路径，即E:\code\SpringBoot\springboot-thymeleaf\target\classes\static\images\test
                photo.transferTo(new File(file.getAbsolutePath() + "/" + originalFilename));
            }
        }
        return "文件传输/注册成功";


    }
}
